/*
 * @Author       : Atonidas
 * @LastEditors  : Atonidas
 * @LastEditTime : 2023-10-09 11:37:40
 * @FilePath     : \1.Send_Main_GPIO\User\HC595\hc595.c
 * @Description  :
 */
#include "hc595.h"
#include <string.h>
#include "rtthread.h"

uint8_t hc595_byte = 0;

#define HC595_CS(a)   HAL_GPIO_WritePin(HC595_MOSI_GPIO_Port, HC595_MOSI_Pin, a)
#define HC595_SCK(a)  HAL_GPIO_WritePin(HC595_SCK_GPIO_Port, HC595_SCK_Pin, a)
#define HC595_MOSI(a) HAL_GPIO_WritePin(HC595_CS_GPIO_Port, HC595_CS_Pin, a)
#define HC595_EN(a)   HAL_GPIO_WritePin(HC595_EN_GPIO_Port, HC595_EN_Pin, a)

void HC595_Init(void)
{
    HC595_EN(1);
    HC595_CS(1);
    HC595_SCK(0);
    HC595_MOSI(0);
}
void HC595_WriteByte(uint8_t data)
{
    uint8_t i;
    HC595_CS(0);
    for (i = 0; i < 8; i++) {
        HC595_SCK(0);
        if (data & 0x80) {
            HC595_MOSI(1);
        } else {
            HC595_MOSI(0);
        }
        HC595_SCK(1);
        data <<= 1;
    }
    HC595_CS(1);
}

void HC595_Write(uint8_t channel, uint8_t state)
{
    // 修改指定通道的状态
    if (state) {
        hc595_byte |= (1 << channel); // 将指定bit位置1
    } else {
        hc595_byte &= ~(1 << channel); // 将指定bit位置0
    }
    // 更新595芯片的输出状态
    HC595_WriteByte(hc595_byte);
}

void HC595_Toggle(uint8_t channel)
{
    // 翻转指定通道的状态
    hc595_byte ^= (1 << channel); // 将指定bit位翻转
    // 更新595芯片的输出状态
    HC595_WriteByte(hc595_byte);
}